package com.dongjiantong.quarantine.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.model.ReportHandleResumes;
import com.dongjiantong.biz.service.ReportHandleResumesService;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.quarantine.enums.FileType;
import com.dongjiantong.quarantine.enums.SupervisionRecordStatus;
import com.dongjiantong.quarantine.mapper.BreedReportsFileMapper;
import com.dongjiantong.quarantine.mapper.SupervisionRecordsMapper;
import com.dongjiantong.quarantine.mapper.SupervisionRecordsSubMapper;
import com.dongjiantong.quarantine.model.BreedReportsFile;
import com.dongjiantong.quarantine.model.SupervisionRecords;
import com.dongjiantong.quarantine.model.SupervisionRecordsSub;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 25/12/17.
 */
@Slf4j
@Service(version = "1.0.0")
public class SupervisionRecordsWriteServiceImpl extends ServiceMybatis<SupervisionRecords> implements SupervisionRecordsWriteService {

    @Resource
    private SupervisionRecordsMapper supervisionRecordsMapper;

    @Resource
    private SupervisionRecordsSubMapper supervisionRecordsSubMapper;

    @Resource
    private BreedReportsFileMapper breedReportsFileMapper;

    @Reference(version = "1.0.0")
    private ReportHandleResumesService reportHandleResumesService;

    /**
     * 创建督查记录
     *
     * @param supervisionRecords 督查记录的主表对象
     * @param mapList            督查记录的子表对象
     * @param toStatus           到状态
     * @return Map<String , Object>
     */
    @Override
    public Map<String, Object> create(SupervisionRecords supervisionRecords, List<Map<String, Object>> mapList, Integer toStatus, LoginInfo loginInfo) {
        Map<String, Object> resultMap = Maps.newHashMap();
        Integer fromStatus = supervisionRecords.getStatus();
        String prefix = ReportNumberMakerUtil.createPrefix("JC", loginInfo.getProvinceId(), loginInfo.getCityId(), loginInfo.getRegionId());
        String number = ReportNumberMakerUtil.create(prefix, supervisionRecordsMapper.findCurrentMaxNumber(prefix));
        supervisionRecords.setNumber(number);
        if (toStatus != null && !fromStatus.equals(toStatus)) {
            supervisionRecords.setStatus(toStatus);
            supervisionRecordsMapper.insert(supervisionRecords);
            supervisionRecordsSubMapper.insertList(buildSupervisionSubList(mapList, supervisionRecords));
            ReportHandleResumes reportHandleResumes = new ReportHandleResumes();
            reportHandleResumes.setFrom_status(fromStatus.byteValue());
            reportHandleResumes.setReport_id(supervisionRecords.getId());
            reportHandleResumes.setReport_number(supervisionRecords.getNumber());
            reportHandleResumes.setTo_status(toStatus.byteValue());
            reportHandleResumes.setType(ReportType.SUPERVISION_RECORD.value());
            reportHandleResumes.setCreated_at(new Date());
            reportHandleResumes.setUpdated_at(new Date());
            reportHandleResumesService.create(reportHandleResumes);

            writeFiles(ReportType.SUPERVISION_RECORD.value(), 1, supervisionRecords.getId(), supervisionRecords.getPhoto_supervision_list(), "photo_supervision_list", "督查记录图片");
            writeFiles(ReportType.SUPERVISION_RECORD.value(), 2, supervisionRecords.getId(), supervisionRecords.getVideo_supervision_list(), "video_supervision_list", "督查记录视频");
            writeFiles(ReportType.SUPERVISION_RECORD.value(), 1, supervisionRecords.getId(), supervisionRecords.getVideo_photo_supervision_list(), "video_photo_supervision_list", "督查记录视频图片");
        } else {
            supervisionRecordsMapper.insert(supervisionRecords);
            supervisionRecordsSubMapper.insertList(buildSupervisionSubList(mapList, supervisionRecords));
        }
        resultMap.put("id", supervisionRecords.getId());
        return resultMap;
    }

    /**
     * 创建督查记录
     *
     * @param supervisionRecords        督查记录的主表对象
     * @param supervisionRecordsSubList 督查记录的子表对象
     * @param toStatus                  到状态
     * @return Map<String , Object>
     */
    @Override
    public Map<String, Object> update(SupervisionRecords supervisionRecords, List<Map<String, Object>> supervisionRecordsSubList, Integer toStatus, LoginInfo loginInfo) {
        Map<String, Object> resultMap = Maps.newHashMap();
        Integer fromStatus = supervisionRecords.getStatus();
        Boolean flag = false;
        if (toStatus != null && !fromStatus.equals(toStatus)) {
            supervisionRecords.setStatus(toStatus);
            flag = supervisionRecordsMapper.updateByPrimaryKey(supervisionRecords) == 1;
            ReportHandleResumes reportHandleResumes = new ReportHandleResumes();
            reportHandleResumes.setFrom_status(fromStatus.byteValue());
            reportHandleResumes.setReport_id(supervisionRecords.getId());
            reportHandleResumes.setReport_number(supervisionRecords.getNumber());
            reportHandleResumes.setTo_status(toStatus.byteValue());
            reportHandleResumes.setType(ReportType.SUPERVISION_RECORD.value());
            reportHandleResumes.setCreated_at(new Date());
            reportHandleResumes.setUpdated_at(new Date());
            reportHandleResumesService.create(reportHandleResumes);
            if (toStatus.equals(SupervisionRecordStatus.PENDING.value())) {
                Map<String , Object> map = Maps.newHashMap();
                map.put("type1",ReportType.SUPERVISION_RECORD.value());
                map.put("relevanceId",supervisionRecords.getId());
                breedReportsFileMapper.deleteByMap(map);
                writeFiles(ReportType.SUPERVISION_RECORD.value(), FileType.PHOTO.value(), supervisionRecords.getId(), supervisionRecords.getPhoto_supervision_list(), "photo_supervision_list", "督查记录图片");
                writeFiles(ReportType.SUPERVISION_RECORD.value(), FileType.VIDEO.value(), supervisionRecords.getId(), supervisionRecords.getVideo_supervision_list(), "video_supervision_list", "督查记录视频");
                writeFiles(ReportType.SUPERVISION_RECORD.value(), FileType.PHOTO.value(), supervisionRecords.getId(), supervisionRecords.getVideo_photo_supervision_list(), "video_photo_supervision_list", "督查记录视频图片");
            }
        } else {
            flag = supervisionRecordsMapper.updateByPrimaryKey(supervisionRecords) == 1;
        }
        updateSupervisionSubList(supervisionRecordsSubList, supervisionRecords);
        resultMap.put("isSuccess", flag);
        return resultMap;
    }

    @Override
    public void updateDeleteFlag(Long id) {
        supervisionRecordsMapper.updateDeleteFlag(id);
    }

    /**
     * 构建自己录的对象list
     *
     * @param mapList            参数list
     * @param supervisionRecords 督查的对象
     * @return List<SupervisionRecordsSub>
     */
    private List<SupervisionRecordsSub> buildSupervisionSubList(List<Map<String, Object>> mapList, SupervisionRecords supervisionRecords) {
        List<SupervisionRecordsSub> supervisionRecordSubs = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            SupervisionRecordsSub supervisionRecordSub = new SupervisionRecordsSub();
            Long supervisionId;
            if (map.get("supervision_id")!=null){
                supervisionId = Long.parseLong(map.get("supervision_id").toString());
            }else {
                supervisionId=null;
            }

            supervisionRecordSub.setSupervision_id(supervisionId == null ? supervisionRecords.getId() : supervisionId);
            supervisionRecordSub.setCode(((Integer) map.getOrDefault("code", null)).longValue());
            supervisionRecordSub.setName((String) map.getOrDefault("name", null));
            supervisionRecordSub.setType((Integer) map.getOrDefault("type", null));
            supervisionRecordSub.setIs_ok((Integer) map.getOrDefault("is_ok", null));
            supervisionRecordSub.setContent((String) map.getOrDefault("content", null));
            supervisionRecordSubs.add(supervisionRecordSub);
        }
        return supervisionRecordSubs;
    }

    /**
     * 跟新督查字表的信息
     *
     * @param mapList            参数
     * @param supervisionRecords 督查主表对表对象
     */
    private void updateSupervisionSubList(List<Map<String, Object>> mapList, SupervisionRecords supervisionRecords) {
        supervisionRecordsSubMapper.deleteBySupervisionId(supervisionRecords.getId());
        supervisionRecordsSubMapper.insertList(buildSupervisionSubList(mapList,supervisionRecords));
    }

    /**
     * 图片或文件的写入
     *
     * @param fileUrls 照片的url
     * @param field    字段名
     * @param state    意义
     */
    private void writeFiles(Integer type1, Integer type2, Long relevanceId, List<String> fileUrls, String field, String state) {
        if (fileUrls != null && !fileUrls.isEmpty()) {
            for (String string : fileUrls) {
                BreedReportsFile breedReportsFile = new BreedReportsFile();
                breedReportsFile.setType1(type1);
                breedReportsFile.setType2(type2);
                breedReportsFile.setField(field);
                breedReportsFile.setAddress(string);
                breedReportsFile.setRelevance_id(relevanceId);
                breedReportsFile.setState(state);
                breedReportsFile.setDate(new Date());
                breedReportsFileMapper.insert(breedReportsFile);
            }
        }
    }
}
